<template>
  <c-back-wrap :loading="loading" go-page="经销商分店关店管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'分店关店业务'">
    <c-title title="基本信息">
      <CustomerBaseInfo
        ref="customerBaseInfo"
        v-model="customerFormData"
        :before-params="paramsJson=>{
          paramsJson.filtersRaw.push({id:'oneCategoryCode',property:'oneCategoryCode',value:'Z230',operator:'<>'})
          $codeOrName(paramsJson.filtersRaw, 'code', 'name')
          return paramsJson
        }"
        :detail="detail"
        :disabled="isEdit"
        @change="handleCustomerChange"
      />
    </c-title>
    <c-title title="经销商-选择待关闭门店">
      <ChangeTable :table-data="shopBusinessDTOS" @change="handleChangeTable" />
    </c-title>
    <c-title v-if="changeResultTableData.length>0" title="经销商-门店建设信息">
      <ShopConstructionInfo :table-data="shopConstructDTOS" type="edit" />
    </c-title>
    <c-title title="经销商-关闭门店更信息">
      <!-- <el-collapse v-model="activeName"> -->
      <c-collapse-item v-for="(d,i) in changeResultTableData" :key="i" :name="i+1">
        <div slot="title" class="change-table-title">
          <span>{{ d.code }}</span>
          <span>{{ d.name }}</span>
          <span>{{ d.shopAddr }}</span>
        </div>
        <QupFormContainer :column="4">
          <el-form ref="form" :model="d" :rules="formRules" label-width="110px">
            <el-form-item prop="isMarketConnect" label="门店是否交接">
              <el-radio-group v-model="d.isMarketConnect">
                <el-radio :value="1" :label="1">是</el-radio>
                <el-radio :value="0" :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="closeReason" label="关店原因" :span="24">
              <el-input v-model="d.closeReason" type="textarea" placeholder="请输入关店原因" maxlength="1024" show-word-limit :autosize="{minRows: 3}" />
            </el-form-item>
            <el-form-item prop="ACCESS069" label="关店附件" :span="24">
              <c-file-list v-model="d.ACCESS069" direct-del :model-id="d.id" view-type="list" type-code="ACCESS069" />
            </el-form-item>
            <el-form-item v-if="[1,'1'].includes(d.isMarketConnect)" prop="ACCESS070" label="交接证明" :rules="genRules(d)" :span="24">
              <c-file-list v-model="d.ACCESS070" direct-del :model-id="d.id" view-type="list" type-code="ACCESS070" />
            </el-form-item>
          </el-form>
        </QupFormContainer>
      </c-collapse-item>
      <!-- </el-collapse> -->
    </c-title>
    <c-title v-if="!NoIsMarketConnect" title="经销商-销售转让信息">
      <QupFormContainer :column="1">
        <el-form ref="form1" :model="formData" :rules="formRules" label-width="130px">
          <el-form-item prop="isTransferSales" label="是否涉及销量转让">
            <el-switch v-model="formData.isTransferSales" :disabled="NoIsMarketConnect" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS071" label="关系证明附件" :span="24">
            <c-file-list v-model="formData.ACCESS071" direct-del :model-id="id" view-type="list" type-code="ACCESS071" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" key="ACCESS111" prop="ACCESS111" label="交接双方现场签订照片" label-width="160px" :span="24">
            <c-file-list v-model="formData.ACCESS111" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="1" label="交接双方现场签订照片模板下载" label-width="180px" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
              <span>交接双方现场签订照片模板下载</span>
              <i class="el-icon-download" />
            </div>
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存草稿</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { shopCloseDetail, shopCloseSave, shopCloseSubmit } from '@/api/channelTask2/shutUpShop'
import { shopListByCustomer, constructShopListByCustomer, downTemplate, getTemplateConfig } from '@/api/channelTask2/change'
import ChangeTable from '../../components/ChangeTable'
import CustomerBaseInfo from '../../components/CustomerBaseInfo'
import ShopConstructionInfo from '../../components/ShopConstructionInfo'

export default {
  name: 'AddEdit',
  components: {
    ChangeTable,
    CustomerBaseInfo,
    ShopConstructionInfo
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      customerFormData: {},
      formData: {
        isTransferSales: '',
        ACCESS071: [],
        ACCESS111: []
      },
      shopLoading: false,
      activeName: 1,
      shopBusinessDTOS: [],
      changeResultTableData: [],
      raw_shopBusinessDTOS: [], // 原始门店数据
      shopConstructDTOSAll: [], // 客户下所有门店建设数据
      shopConstructDTOS: [],
      ACCESS111: {}
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    formRules() {
      const hasIsTransferSales = [1, '1'].includes(this.formData.isTransferSales)
      return {
        isMarketConnect: [{ required: true, message: '请选择门店是否交接', trigger: 'change' }],
        // ACCESS069: [{ required: true, validator: this.validatorFile('关店附件', true), trigger: 'change' }],
        isTransferSales: [{ required: true, message: '请选择是否涉及销量转让', trigger: 'change' }],
        closeReason: [{ required: true, message: '请输入关店原因', trigger: 'change' }],
        ACCESS071: [{ required: hasIsTransferSales, validator: this.validatorFile('关系证明附件', hasIsTransferSales), trigger: 'change' }],
        ACCESS111: [{ required: !this.NoIsMarketConnect, validator: this.validatorFile('交接双方现场签订照片', hasIsTransferSales), trigger: 'change' }]
      }
    },
    // 所有门店是否交接为否
    NoIsMarketConnect() {
      return this.changeResultTableData.length > 0 && this.changeResultTableData.every(e => ![1, '1'].includes(e.isMarketConnect))
    }
  },
  watch: {
    NoIsMarketConnect: {
      handler(v) {
        if (v) {
          this.$set(this.formData, 'isTransferSales', 0)
        }
      },
      immediate: true
    }
  },
  created() {
    this.id && this.getDetailData()
    this.templateConfig()
  },
  methods: {
    getDetailData() {
      this.loading = true
      return shopCloseDetail(this.id).then(res => {
        this.detail = res.data

        this.changeResultTableData = this.detail.shopBusinessDTOS.filter(e => [1, '1'].includes(e.isChange)).map(e => {
          e.afterBusinessType = (e.businessType || '').split(',')
          e.afterBusinessTypeName = (e.businessTypeName || '').split(',')
          return e
        })

        this.getShopData(this.detail.customerCode, false)

        this.shopConstructDTOS = this.detail.shopConstructDTOS
        this.initFormData()
      }).finally(() => {
        this.loading = false
      })
    },
    initFormData() {
      Object.keys(this.formData).forEach(k => {
        if (this.detail[k] !== undefined) {
          this.$set(this.formData, k, this.detail[k])
        }
      })
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleChangeTable(tableData) {
      this.changeResultTableData = tableData
      this.shopConstructDTOS = this.shopConstructDTOSAll.filter(e => {
        return this.changeResultTableData.some(ee => ee.code === e.shopCode)
      })
    },
    getShopData(customerCode, getShopConstruct = true) {
      shopListByCustomer(customerCode).then(res => {
        const t = res.data.map(e => {
          e.afterBusinessType = (e.businessType || '').split(',')
          e.afterBusinessTypeName = (e.businessTypeName || '').split(',')
          if (e.isMarketConnect === undefined) {
            e.isMarketConnect = 0
          }
          return e
        })
        this.raw_shopBusinessDTOS = t
        this.shopBusinessDTOS = this.$deepClone(t).map(e => {
          const tmp = this.changeResultTableData.find(ee => ee.code === e.code && ee.name === e.name)
          return tmp || e
        })
      })
      if (!getShopConstruct) {
        return
      }
      constructShopListByCustomer(customerCode).then(res => {
        this.shopConstructDTOSAll = res.data
      })
    },
    handleCustomerChange(customerCode) {
      this.changeResultTableData = []
      this.raw_shopBusinessDTOS = []
      this.shopBusinessDTOS = []
      this.shopConstructDTOS = []
      this.shopConstructDTOSAll = []
      if (customerCode) {
        this.getShopData(customerCode)
      }
    },
    genRules(d) {
      return {
        required: [1, '1'].includes(d.isMarketConnect),
        validator: (r, v, c) => {
          if ([1, '1'].includes(d.isMarketConnect) && (!v || v.length <= 0)) {
            c(new Error('请上传交接证明'))
          } else {
            c()
          }
        }
      }
    },
    validatorFile(msg, required) {
      return (r, v, c) => {
        if (required && (!v || v.length <= 0)) {
          c(new Error(`请上传${msg}`))
        } else {
          c()
        }
      }
    },
    hasChange() {
      // const raw = this.raw_shopBusinessDTOS
      const result = this.changeResultTableData
      if (result.length <= 0) {
        this.$message.warning(`选择待关闭门店!`)
        return false
      }
      // for (const r of result) {
      //   const t = raw.find(e => r.code === e.code && r.name === e.name)
      //   if (!t) {
      //     continue
      //   }

      //   const is_change = r.isMarketConnect !== t.isMarketConnect
      //   if (!is_change) {
      //     this.$message.warning(`门店【${r.name}】信息无变更!`)
      //     return false
      //   }
      // }
      return true
    },
    async validate() {
      if (!this.hasChange()) {
        return Promise.reject(false)
      }
      await this.$refs.customerBaseInfo.validate()
      if (this.changeResultTableData.length <= 0) {
        this.$message.warning('请选择待关闭门店!')
        return Promise.reject(false)
      }
      for (let i = 0; i < this.shopConstructDTOS.length; i++) {
        const t = this.shopConstructDTOS[i]
        if (!t.handleType) {
          this.$message.warning(`请选择【经销商-门店建设信息】第${i + 1}行,门店建设数据处理方式!`)
          return Promise.reject(false)
        }
      }
      const forms = this.$refs.form
      if (forms) {
        for (let i = 0; i < forms.length; i++) {
          await forms[i].validate().catch(() => {
            this.activeName = i
            return Promise.reject(false)
          })
        }
      }
      if (this.$refs.form1) {
        await this.$refs.form1.validate()
      }
      return Promise.resolve(true)
    },
    getPostData(isSubmit) {
      const data = {}
      if (this.id) {
        Object.assign(data, this.$deepClone(this.detail))
      }
      Object.assign(data, this.$deepClone(this.customerFormData))

      let shopBusinessDTOS = this.$deepClone(this.changeResultTableData)

      if (isSubmit) {
        const rawData = this.$deepClone(this.raw_shopBusinessDTOS).filter(e => !shopBusinessDTOS.some(ee => e.code === ee.code))
        shopBusinessDTOS.push(...rawData)
      }

      shopBusinessDTOS = shopBusinessDTOS.map(e => {
        e.attachmentDTOS = [
          ...this.$getFiles(e.ACCESS069 || []),
          ...this.$getFiles(e.ACCESS070 || [])
        ]
        delete e.ACCESS069
        delete e.ACCESS070
        e.afterBusinessType = e.afterBusinessType.join(',')
        e.afterBusinessTypeName = e.afterBusinessTypeName.join(',')
        return e
      })

      data.shopBusinessDTOS = shopBusinessDTOS

      data.shopConstructDTOS = this.$deepClone(this.shopConstructDTOS)

      Object.assign(data, this.$deepClone(this.formData))
      data.attachmentDTOS = [
        ...this.$getFiles(data.ACCESS071 || []),
        ...this.$getFiles(data.ACCESS111 || [])
      ]
      delete data.ACCESS071
      delete data.ACCESS111

      data.type = 'G'
      return data
    },
    handleSave() {
      return shopCloseSave(this.getPostData()).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop(!this.id ? 'opCondition' : 'onPage')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        return shopCloseSubmit(this.getPostData(true)).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop(!this.id ? 'opCondition' : 'onPage')
        })
      })
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.change-table-title{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>span{
    color: #333;
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }
}
</style>
